/*
 * Copyright (C) 2013 Manoel Afonso Filho
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package agimagem.fitness;

import agimagem.populacao.Individuo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Função fitness. Utiliza o conceito de entropia para o cálculo. Quanto maior
 * o valor do fitness, melhor.
 * @author Manoel Afonso Filho
 */
public class Fitness {

    private static Logger log = LogManager.getLogger(Fitness.class.getName());

    /**
     * Plaintext original.
     */
    public static byte[] plaintext;

    /**
     *
     * @param ind
     * @return
     */
    public static double calcular(Individuo ind){
        byte[] imagem = ind.getCiphertext();
        double f = entropia(contarOcorrencias(imagem), imagem.length);
        return f;
    }

    public static double entropia(int[] contarOcorrencias, int tam) {
        double p;
        double entropia = 0;
        for (int i = Byte.MIN_VALUE; i < Byte.MAX_VALUE + 1; i++) {
            if (contarOcorrencias[i + 128] == 0) {
                continue;
            }
            p = 1.0 * contarOcorrencias[i + 128] / tam;
            entropia -= p * logOfBase(256, p);
        }
        return entropia;
    }

    public static int[] contarOcorrencias(byte[] dados) {
        int[] ocorrencias = new int[256];
        for (int i = 0; i < dados.length; i++) {
            ocorrencias[dados[i] + 128] += 1;
        }
        return ocorrencias;
    }

    public static double logOfBase(int base, double num) {
        return Math.log(num) / Math.log(base);
    }

}
